import { onBeforeUnmount, onMounted, Ref, ref,markRaw } from 'vue';
import * as echarts from 'echarts';

export function useChart(
  chartRef: Ref<HTMLAnchorElement | null>,
  getData: any
) {
  const chartInstance = ref<echarts.ECharts | null>(null);
  const initChart = async() => {
    if (chartRef.value) {
        //echarts自带响应式与vue的响应式冲突了,用markRaw方法取消echarts的响应式
      chartInstance.value =markRaw(echarts.init(chartRef.value)) 
    const options = await getData();
      chartInstance.value.setOption(options);
    }
  };
  const resizeChart = () => {
    chartInstance.value?.resize();
  };
  onMounted(() => {
    initChart();
    window.addEventListener('resize', resizeChart);
  });

onBeforeUnmount(() => {
  chartInstance.value?.dispose(); // 释放图表所占用的资源,清理内存
  window.removeEventListener('resize', resizeChart);
})
}
